package servlet;

import bean.HouseInfo;
import bean.HouseType;
import utils.DBUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

@WebServlet("/add")
public class AddServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ArrayList<HouseType> list = new ArrayList<>();
        //1.编写sql语句
        String sql = "select * from house_type";
        //2.调用工具类得到结果集
        ResultSet rs = DBUtil.query(sql);
        //3.通过结果集循环得到数据
        try {
            while (rs.next()) {
                int id = rs.getInt(1);
                String type = rs.getString(2);
                //4.将数据封装成对象存入集合
                HouseType house = new HouseType(id,type);
                list.add(house);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //5.将集合添加到request域中
        request.setAttribute("list",list);
        //6.将集合转发给jsp显示
        request.getRequestDispatcher("/WEB-INF/add.jsp").forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //0.处理乱码问题
        request.setCharacterEncoding("utf-8");
        ArrayList<HouseInfo> list = new ArrayList<>();
        //1.编写sql语句
        String sql = "insert into house_info values (?,?,?,?,?,?,?)";
        //2.获取表单数据
        String leaseMode = request.getParameter("leaseMode");
        String rent = request.getParameter("rent");
        String contacts = request.getParameter("contacts");
        String depositMethod = request.getParameter("depositMethod");
        String type = request.getParameter("type");
        String address = request.getParameter("address");
        //3.调用工具类得到受影响的行数
        int i = DBUtil.update(sql,null,leaseMode,rent,contacts,depositMethod,type,address);
        //4.使用影响行数判断添加是否成功
        if(i>0){
            //重定向，跳转刷新页面
            response.sendRedirect("/list");
        }else{
            //5.将提示信息添加到request域中
            request.setAttribute("msg","添加失败");
            //6.将集合转发给jsp显示
            request.getRequestDispatcher("/WEB-INF/msg.jsp").forward(request,response);
        }


    }
}
